const vscode = require("vscode");
const fs = require('fs');
const zlib = require('zlib');
const { Buffer } = require('buffer');
const os = require('os');
const path = require('path');

class files {
    constructor() {
        this.ctx = null
    }

    setCtx(ct) {
        this.ctx = ct
        this._init()
    }
    _init() {
        const that = this;
        let disposable = vscode.workspace.onDidSaveTextDocument((document) => {
            // 检查保存的文件是否是您要监听的文件
            // if (document.fileName === '/path/to/file.txt') {
            // 处理文件保存事件
            console.log(`File saved: ${document.fileName}`);
            if (document.fileName.indexOf('/daodan-temp-') != -1&&document.fileName.endsWith('js') != -1) {
                that.readFile(document.fileName, (status, data) => {
                    if (status) {
                        console.log('文件内容：', data)
                        that.compressAndBase64Encode(data).then((res) => {
                            console.log('压缩内容：', res)
                            const abid = that.ctx.globalState.get(document.fileName);
                            if (!abid) {
                                vscode.window.showErrorMessage('文件异常，请备份内容后，重新打开文件！')
                                return
                            }
                            let ab = that.ctx.globalState.get(abid)
                            if (!ab) {
                                vscode.window.showErrorMessage('文件异常，请备份内容后，重新打开文件~')
                                return
                            }
                            ab = JSON.parse(ab)
                            ab.content = res;
                            ab.time = Date.now();
                            that.ctx.globalState.update(abid, JSON.stringify(ab));
                        })
                    }
                })
            }
            // }
        });
        this.ctx.subscriptions.push(disposable);
        let disposable2 = vscode.workspace.onDidCloseTextDocument((document) => {
            // 检查保存的文件是否是您要监听的文件
            // if (document.fileName === '/path/to/file.txt') {
            // 处理文件保存事件
            console.log(`File close: ${document.fileName}`);
            if (document.fileName.indexOf('/daodan-temp-') != -1){
                that.removeFile(document.fileName);
                let abid = that.ctx.globalState.get(document.fileName)
                if (abid) {
                    that.ctx.globalState.update(document.fileName, null)
                    that.ctx.globalState.update(abid + '_file', null)
                }
            }
            // }
        });
        this.ctx.subscriptions.push(disposable2);
        let disposable_openTmpFile = vscode.commands.registerCommand(
            "daodan.openTmpFile",
            function (da) {
                that.openTmpFile(da.name, da.content, da.id);
            }
        );
        this.ctx.subscriptions.push(disposable_openTmpFile);

    }
    compressAndBase64Encode(content) {
        return new Promise((resolve, reject) => {
            const gzip = zlib.createGzip();
            let compressData = Buffer.alloc(0);
            gzip.on('data', (chunk) => {
                compressData = Buffer.concat([compressData, chunk]);
            });
            gzip.on('end', () => {
                const base64Data = compressData.toString('base64');
                resolve(base64Data);
            });
            gzip.end(content);
        });
    }

    removeFile(filePath) {
        fs.unlink(filePath, (err) => {
            if (err) {
                console.log('文件删除报错：', err)
            };
            console.log('文件已被删除');
        });
    }
    openTmpFile(name, content, id) {
        const f = this.writeTempFile(name, content)
        if (f) {
            if (id) {
                const oldfile = this.ctx.globalState.get(id + '_file')
                if (oldfile) {
                    this.ctx.globalState.update(oldfile, null);
                    this.removeFile(oldfile);
                }
                this.ctx.globalState.update(id + '_file', f);
                this.ctx.globalState.update(f, id);
            }
            this.openFile(f);
        }
    }
    readFile(filePath, callback) {
        fs.readFile(filePath, 'utf8', (err, data) => {
            if (err) {
                console.error(err);
                callback(false)
                return;
            }
            // console.log(data);
            callback(true, data);
        });
    }
    writeTempFile(name, content) {
        const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'daodan-temp-'));
        let newFile = tempDir ;
        console.log(name.indexOf('.') !== -1,(name.length-name.indexOf('.')));
        if(name.indexOf('.') !== -1&&(name.length-name.indexOf('.'))<=5 ){
            newFile+= `/${name}`;
        }else{
            newFile+= `/${name}.js`;
        }
        
        // 创建新文件的路径  
        //   let text = 'Hello, World!'; // 新文件的内容  
        //   console.log('fff',newFile);
        // 创建文件 
        fs.access(newFile, fs.constants.F_OK, (err) => {
            if (!err) {
                fs.unlinkSync(newFile);
            }
        });
        if (!content) {
            content = ''
        }
        //   console.log('fff',newFile,'ok');
        fs.writeFile(newFile, content, function (err) {
            if (err) throw err;
            console.log('Temporary file created successfully.');
        });
        return newFile
    }
    openFile(filePath) {
        if (!filePath) {
            return
        }
        vscode.workspace.openTextDocument(filePath).then((document) => {
            vscode.window.showTextDocument(document);
        }).catch((error) => {
            vscode.window.showErrorMessage(`Failed to open file: ${error}`);
        });
    }
}

module.exports = {
    files,
};


